﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DictinaryTools
{
    public class ThreadMethod
    {
        /// <summary>
        /// 线程开始事件
        /// </summary>
        public event EventHandler threadStartEvent;
        /// <summary>
        /// 线程执行时事件
        /// </summary>
        public event EventHandler threadEvent;
        /// <summary>
        /// 线程结束事件
        /// </summary>
        public event EventHandler threadEndEvent;

        public void runMethod(List<string> datalist, SqlSugarClient db,string filepath)
        {
            List<DataTable> tbList = new List<DataTable>();
            int count = datalist.Count;      //执行多少次
            threadStartEvent.Invoke(count, new EventArgs());//通知主界面,我开始了,count用来设置进度条的最大值
            if (datalist!=null && datalist.Count>0)
            {
                GenteFiles(filepath, datalist);
            }
            string lasttablename = "Home_LightBlue"; //上一张表名称
            string nexttablename = "Home_LightBlue"; //下一张表名称
            for (int i = 0; i < datalist.Count; i++)
            {
                Thread.Sleep(10);//休息10毫秒,模拟执行大数据量操作
                #region 获取表结构
                var datamodel = db.Ado.GetDataTable(string.Format(@"SELECT
    --表名=case   when   a.colorder=1   then   d.name   else   ''   end,
    --表说明=case   when   a.colorder=1   then   isnull(f.value,'')   else   ''   end,
    字段序号=a.colorder,
    字段名=a.name,
    标识=case   when   COLUMNPROPERTY(   a.id,a.name,'IsIdentity')=1   then   '√'else   ''   end,
    主键=case   when   exists(SELECT   1   FROM   sysobjects   where   xtype='PK'   and   name   in   (
        SELECT   name   FROM   sysindexes   WHERE   indid   in(
            SELECT   indid   FROM   sysindexkeys   WHERE   id   =   a.id   AND   colid=a.colid
        )))   then   '√'   else   ''   end,
    类型=b.name,
    占用字节数=a.length,
    长度=COLUMNPROPERTY(a.id,a.name,'PRECISION'),
    小数位数=isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0),
    允许空=case   when   a.isnullable=1   then   '√'else   ''   end,
    默认值=isnull(e.text,''),
    字段说明=isnull(g.[value],'')
FROM   syscolumns   a
    left join   systypes   b   on   a.xusertype=b.xusertype
    inner join   sysobjects   d   on   a.id=d.id     and   d.xtype='U'   and     d.name<>'dtproperties'
    left join   syscomments   e   on   a.cdefault=e.id
    left join   sys.extended_properties   g   on   a.id=g.major_id   and   a.colid=g.minor_id
    left join   sys.extended_properties   f   on   d.id=f.major_id   and   f.minor_id=0
where d.name='{0}'         --如果只查询指定表,加上此条件
order by a.id,a.colorder", datalist[i]));
                #endregion
                tbList.Add(datamodel);
                if (datalist.Count>(i+1) && datalist[i + 1] != null && !string.IsNullOrEmpty(datalist[i + 1]))
                {
                    nexttablename = datalist[i + 1];
                }
                GeneteReportFiles(filepath, datalist[i], datamodel,i, lasttablename, nexttablename);
                lasttablename = datalist[i];

                threadEvent.Invoke(i, new EventArgs());//通知主界面我正在执行,i表示进度条当前进度
            }
            threadEndEvent.Invoke(new object(), new EventArgs());//通知主界面我已经完成了
        }

        public void GenteFiles(string filepath, List<string> datalist)
        {
            #region  1.先读取静态文件生成到指定目录下
            if (!Directory.Exists(filepath))
            {
                Directory.CreateDirectory(filepath);
            }
            string secondpath = filepath + "\\Report_files";
            if (!Directory.Exists(secondpath))
            {
                Directory.CreateDirectory(secondpath);
            }
            var srcPath = @"..\..\StaticFile";
            string fullpath = Path.GetFullPath(srcPath);
            CopyDirectory(fullpath, secondpath);
            var mainpagesrcPath = @"..\..\StaticFile\mainpage";
            string mainpagefullpath = Path.GetFullPath(mainpagesrcPath);
            CopyDirectory(mainpagefullpath, filepath);
            #endregion

            #region 生成左边的菜单目录
            string head = @"<html>
<head>
<meta http-equiv='Content - Type' content='text/html; charset= utf-8'>
        <title > Report 1
           </title >
           <link href = 'LightBlue_Theme.css' type = 'text/css' rel = 'stylesheet'>
                <base target = 'Doc_Frame'>
                 </head >
                  <body class='browserBody'>
<script language = 'JavaScript'>
var bV=parseInt(navigator.appVersion);
        var uA = navigator.userAgent.toLowerCase();
        var NS4 = (document.layers) ? true : false;
        var NS6 = false;
        var Op = false;
        var IE4 = false;
if (uA.indexOf('opera') != -1)
   Op=true;
else if (uA.indexOf('msie') != -1)
   IE4=(bV>=4)?true:false;
else if (uA.indexOf('netscape') != -1 || uA.indexOf('mozilla') != -1)
   NS6=(bV>=5)?true:false;
var ver4 = (NS4 || NS6 || IE4) ? true : false;
</script><br/>";

            StringBuilder sb = new StringBuilder();
            for (int i=0;i< datalist.Count;i++)
            {
                sb.AppendFormat(@"<div class='sngl' id='elmt{1}item'><nobr><img height='15' width='15' src='i_corner.gif' border='0'><a href='{0}.html#{2}'><img height='15' width='15' title='表 {0}' src='i_normal.gif' border='0' name='imNrml'></a><a class='Browser' href='{0}.html#{2}'>表 {0}</a></nobr></div>", datalist[i],(i+1),(i+1)*2);
                sb.Append("\r\n");
            }
            string end = "<br/><br/></body></html>";

            string mainpagehtml = head + sb.ToString() + end;
            string mainpagefile = secondpath + "\\Report.html";
            if (File.Exists(mainpagefile))
            {
                File.Delete(mainpagefile);
            }
            File.AppendAllText(secondpath + "\\Report.html", mainpagehtml);
            #endregion
        }

        /// <summary>
        /// 根据datatable获得列名
        /// </summary>
        /// <param name="dt">表对象</param>
        /// <returns>返回结果的数据列数组</returns>
        public static string[] GetColumnsByDataTable(DataTable dt)
        {
            string[] strColumns = null;
            if (dt.Columns.Count > 0)
            {
                int columnNum = 0;
                columnNum = dt.Columns.Count;
                strColumns = new string[columnNum];
                for (int i = 0; i < dt.Columns.Count; i++) //取出前面两个字段
                {
                    strColumns[i] = dt.Columns[i].ColumnName;
                }
            }
            return strColumns;
        }


        public void GeneteReportFiles(string filepath, string tablename, DataTable dt, int index,string lasttablename,string nexttablename)
        {

            string head = string.Format(@"<html>
<head>
<meta http-equiv='Content - Type' content='text/html; charset = utf-8'>
        <title> Report 1
           </title >
           <link href = 'LightBlue_Theme.css' type = 'text/css' rel = 'stylesheet'>
                </head>
                 <body>
                 <h2>
                 <a name = '2' >表_{0}</a>
                  </h2>
                  <h3>
                  <a name = '3' > 表_{0}的栏的清单 </ a >
                   </h3 >
                   <table class='Grid' border='1' cellspacing='1' width='100%'>", tablename);

            string tbhead = "<tr>";
            string[] headlist=GetColumnsByDataTable(dt);
            for (int j=0;j<headlist.Length;j++)
            {
                tbhead +=string.Format(@"<td class='Header'>
                                            <p align = 'left'> {0}
                                            </p>
                                         </td> ", headlist[j].ToString());
            }
            tbhead += "</tr>";
            StringBuilder sb = new StringBuilder();

            try
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    sb.Append("<tr>");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (Convert.ToBoolean(i % 2))
                        {
                            sb.AppendFormat(@"<td>
                                   <p align='left'>{0}
                                   </p>
                                   </td> ", dt.Rows[i][j].ToString());
                        }
                        else
                        {
                            sb.AppendFormat(@"<td class='TD2'>
                                   <p align='left'>{0}
                                   </p>
                                   </td> ", dt.Rows[i][j].ToString());
                        }

                    }

                    sb.Append("</tr>");
                }
            }
            catch (Exception ex)
            {

                throw;
            }

            string end =string.Format( @"</table><br/>
<hr />
<table ><tr>
<td><table class='NavGroup'><tr><td><a class='NavButton' href='{1}.html'>上一页</a></td></tr></table></td>
<td width = 4 ></ td >
<td><table class='NavGroup'><tr><td><a class='NavButton' href='Home_LightBlue.html'>主页</a></td></tr></table></td>
<td width = 4 ></ td >
<td ><table class='NavGroup'><tr><td><a class='NavButton' href='{2}.html'>下一页</a></td></tr></table></td></tr></table>
<br/>
<br/>
</body>
</html>",index+1,lasttablename, nexttablename);
            string secondpath = filepath + "\\Report_files";
            string mainpagehtml = head + tbhead+ sb.ToString() + end;
            string mainpagefile = secondpath + "\\"+ tablename + ".html";
            if (File.Exists(mainpagefile))
            {
                File.Delete(mainpagefile);
            }
            File.AppendAllText(mainpagefile, mainpagehtml);

        }

        public static void CopyDirectory(string srcPath, string destPath)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath); FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //获取目录下（不包含子目录）的文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)     //判断是否文件夹
                    {
                        if (!Directory.Exists(destPath + "\\" + i.Name))
                        {
                            Directory.CreateDirectory(destPath + "\\" + i.Name);   //目标目录下不存在此文件夹即创建子文件夹
                        }
                        CopyDirectory(i.FullName, destPath + "\\" + i.Name);    //递归调用复制子文件夹
                    }
                    else
                    {
                        File.Copy(i.FullName, destPath + "\\" + i.Name, true);      //不是文件夹即复制文件，true表示可以覆盖同名文件
                    }
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }
    }
}
